<?php

/**
 * ECSHOP 用户中心
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: user.php 16643 2009-09-08 07:02:13Z liubo $
*/

define('IN_ECS', true);
define('ECS_ADMIN', true);

require(dirname(__FILE__) . '/includes/init.php');
/* 载入语言文件 */
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');
//if ($_SESSION['user_id'] > 0)
//{
//	$smarty->assign('user_name', $_SESSION['user_name']);
//}
$act = isset($_GET['act']) ? $_GET['act'] : '';
//$user_id = $_SESSION['user_id'];



/* 举报 */
if ($act == 'app_report')
{
	$cid=isset($_GET['cid']) ? intval($_GET['cid']) : '';
	$sql=" update ".$GLOBALS['ecs']->table('article_comment')." set report = 1 where comment_id='$cid'";
	if($GLOBALS['db']->query($sql)){
		$uu['error']=0;
		$uu['message']='举报成功';
	}else{
		$uu['error']=1;
		$uu['message']='举报失败';
	}
	echo json_encode($uu);
	
	
}
/* 插入点赞 */
elseif ($act == 'app_click_good')
{
	$cid=isset($_GET['cid']) ? intval($_GET['cid']) : '';
	$uid=isset($_GET['uid']) ? intval($_GET['uid']): '';
	$bid=isset($_GET['bid']) ? intval($_GET['bid']): '';
	$num=isset($_GET['num']) ? intval($_GET['num']): '';
	$size=isset($_GET['size']) ? intval($_GET['size']): '';
	$type= isset($_GET['type']) ? $_GET['type'] :  '';
	$num=$num*$size;
	$sql=" select id from ".$GLOBALS['ecs']->table('good_mark')." where comment_id='$cid' and user_id='$uid'";
	$good=$db->getOne($sql);
	$sql=" select good_count from ".$GLOBALS['ecs']->table('article_comment')." where comment_id='$cid'";
	$good_count=$db->getOne($sql);
	if($good){
		$sql=" delete from".$GLOBALS['ecs']->table('good_mark')." where id ='$good'";
		$delete_good=$GLOBALS['db']->query($sql);
		if($delete_good){
			$good_count=$good_count-1;
			$sql=" update ".$GLOBALS['ecs']->table('article_comment')." set good_count='$good_count' where comment_id='$cid'";
			$GLOBALS['db']->query($sql);
			$uu['error']=0;
		}else{
			$uu['error']=1;
		}
		
		
	}else{
		$sql=" insert into ".$GLOBALS['ecs']->table('good_mark')." (user_id,comment_id,create_time) value('$uid','$cid','".gmtime()."')";
		$add_goos=$GLOBALS['db']->query($sql);
		if($add_goos){
			$good_count=$good_count+1;
			$sql=" update ".$GLOBALS['ecs']->table('article_comment')." set good_count='$good_count' where comment_id='$cid'";
			$GLOBALS['db']->query($sql);
			$uu['error']=0;
		}else{
			$uu['error']=1;
		}
		
	}
	if($uu['error']==0){
		$sql = " select g.id,a.content,a.comment_id,a.id_value,a.good_count,a.add_time,a.parent_id,a.parent_user_id,a.parent_user_name,a.parent_user_nick,u.user_nick,u.user_name,u.user_id,u.avatar from ".$GLOBALS['ecs']->table('article_comment')." as a ".
		" left join ".$GLOBALS['ecs']->table('users')." as u ON a.user_id=u.user_id".
		" left join ".$GLOBALS['ecs']->table('good_mark')." as g on g.comment_id=a.comment_id and g.user_id='$uid'".
		" where a.id_value = '$bid' and  a.status =1 and a.comment_type ='$type' order by a.add_time LIMIT $num,$size  ";
		$uu['all']=$GLOBALS['db']->getAll($sql);
		foreach($uu['all'] as $key=> $var){
			$uu['all'][$key]['add_time'] = local_date($GLOBALS['_CFG']['time_format'],$uu['all'][$key]['add_time']);
				if($uu['all'][$key]['avatar'])
			{
				$uu['all'][$key]['avatar'] =  OSS_HOST.$uu['all'][$key]['avatar'];
			}
		}
		$sql = " select g.id,a.content,a.comment_id,a.id_value,a.good_count,a.add_time,a.parent_id,a.parent_user_id,a.parent_user_name,a.parent_user_nick,u.user_nick,u.user_name,u.user_id,u.avatar from ".$GLOBALS['ecs']->table('article_comment')." as a ".
		" left join ".$GLOBALS['ecs']->table('users')." as u ON a.user_id=u.user_id".
		" left join ".$GLOBALS['ecs']->table('good_mark')." as g on g.comment_id=a.comment_id and g.user_id='$uid'".
		" where a.id_value = '$bid' and  a.status =1 and a.comment_type ='$type' order by a.good_count DESC LIMIT 0,3 ";
		$uu['hot']=$GLOBALS['db']->getAll($sql);
		foreach($uu['hot'] as $key=> $var){
			$uu['hot'][$key]['add_time'] = local_date($GLOBALS['_CFG']['time_format'],$uu['hot'][$key]['add_time']);
			if($uu['hot'][$key]['avatar'])
			{
				$uu['hot'][$key]['avatar'] =  OSS_HOST.$uu['hot'][$key]['avatar'];
			}
		}
	}else{
		$uu['message']='点赞失败';
	}
	echo json_encode($uu);
	
	
}
/* 插入评论 */
elseif ($act == 'app_comment')
{
	$content = isset($_GET['content']) ? $_GET['content'] : '';
	$bid     = isset($_GET['bid']) ? $_GET['bid'] :  '';
	$uid     = isset($_GET['uid']) ? $_GET['uid'] :  '';
	$uname   = isset($_GET['uname']) ? $_GET['uname'] :  '';
	$punick   = isset($_GET['punick']) ? $_GET['punick'] :  '';
	$parent  = isset($_GET['parent']) ? $_GET['parent'] : '0';
	$puname  = isset($_GET['puname']) ? $_GET['puname'] : '';
	$type  = isset($_GET['type']) ? $_GET['type'] : '';
	$puid  = isset($_GET['puid']) ? $_GET['puid'] : '0';
	if($content==""){
		$uu['error']='1';
		$uu['message']="评论为空不能发表";
	}else{
		$sql="insert into ".$GLOBALS['ecs']->table('article_comment').
		" ( comment_type,parent_user_nick,parent_user_name,parent_user_id,id_value, user_name, content, add_time, ip_address, status, parent_id, user_id) value ".
		" ('".$type ."','".$punick."','".$puname."','".$puid."','".$bid."','".$uname."','".$content."','".gmtime()."','".real_ip()."','1','".$parent."','".$uid."')";
		$GLOBALS['db']->query($sql);
		$uu['error']='0';
		$uu['message']="评论成功";
	}
	echo json_encode($uu);
	
	
}

/* 获取评论 */
elseif ($act == 'app_get_comment')
{
//	$content = isset($_GET['content']) ? $_GET['content'] : '';
	$bid     = isset($_GET['bid']) ? $_GET['bid'] :  '';
	$uid     = isset($_GET['uid']) ? $_GET['uid'] :  '';
	$num     = isset($_GET['num']) ? $_GET['num'] :  '';
	$size     = isset($_GET['size']) ? $_GET['size'] :  0;
	$type     = isset($_GET['type']) ? $_GET['type'] :  '';
	$num=$num*$size;
	$where   =" ";
	if($size!=0){
		$where   =" LIMIT $num,$size";
	}
	
//	$uname   = isset($_GET['uname']) ? $_GET['uname'] :  '';
//	$parent  = isset($_GET['parent']) ? $_GET['parent'] : '0';
	$sql = " select g.id,a.content,a.comment_id,a.id_value,a.good_count,a.add_time,a.parent_id,a.parent_user_id,a.parent_user_name,a.parent_user_nick,u.user_nick,u.user_name,u.user_id,u.avatar from ".$GLOBALS['ecs']->table('article_comment')." as a ".
	" left join ".$GLOBALS['ecs']->table('users')." as u ON a.user_id=u.user_id".
	" left join ".$GLOBALS['ecs']->table('good_mark')." as g on g.comment_id=a.comment_id and g.user_id='$uid'".
	" where a.id_value = '$bid' and  a.status =1 and a.comment_type = '$type' order by a.add_time ".$where;
	$uu=$GLOBALS['db']->getAll($sql);
	foreach($uu as $key=> $var){
		$uu[$key]['add_time'] = local_date($GLOBALS['_CFG']['time_format'],$uu[$key]['add_time']);
		if($uu[$key]['avatar'])
		{
			$uu[$key]['avatar'] =  OSS_HOST.$uu[$key]['avatar'];
		}
	}
//	$uu['add_time']=local_date($GLOBALS['_CFG']['time_format'],$uu['add_time']);
	echo json_encode($uu);
	
	
	
}

/* 获取评论 */
elseif ($act == 'app_get_hotComment')
{
	$bid     = isset($_GET['bid']) ? $_GET['bid'] :  '';
	$uid     = isset($_GET['uid']) ? $_GET['uid'] :  '';
	$type     = isset($_GET['type']) ? $_GET['type'] :  '';
	$where =" ";
	$id =" ";
	if($uid){
		$where =" left join ".$GLOBALS['ecs']->table('good_mark')." as g on g.comment_id=a.comment_id and g.user_id='$uid'";
		$id =" g.id,";
	}
	$sql = " select ".$id.
	"a.content,a.comment_id,a.id_value,a.good_count,a.add_time,a.parent_id,a.parent_user_id,a.parent_user_name,a.parent_user_nick,u.user_nick,u.user_name,u.user_id,u.avatar from ".$GLOBALS['ecs']->table('article_comment')." as a ".
	" left join ".$GLOBALS['ecs']->table('users')." as u ON a.user_id=u.user_id".$where.
//	" left join ".$GLOBALS['ecs']->table('good_mark')." as g on g.comment_id=a.comment_id and g.user_id='$uid'".
	" where a.id_value = '$bid' and  a.status =1 and a.comment_type = '$type' order by a.good_count DESC LIMIT 0,3 ";
	$uu=$GLOBALS['db']->getAll($sql);
	foreach($uu as $key=> $var){
		$uu[$key]['add_time'] = local_date($GLOBALS['_CFG']['time_format'],$uu[$key]['add_time']);
		if($uu[$key]['avatar'])
		{
			$uu[$key]['avatar'] =  OSS_HOST.$uu[$key]['avatar'];
		}
	}
//	$uu['add_time']=local_date($GLOBALS['_CFG']['time_format'],$uu['add_time']);
	echo json_encode($uu);
	
	
	
}
/* 获取我的消息消息列表*/
//elseif ($act == 'get_message_list')
//{
//	$bid  = isset($_GET['bid']) ? $_GET['bid'] :  '';
//	$uid  = isset($_GET['uid']) ? $_GET['uid'] :  1;
//	$sql  = "select * from ".$GLOBALS['ecs']->table('user_message')." as m ".
//	" left join ".$GLOBALS['ecs']->table('message_cat')." as c on c.cat_id=m.cat_id ".
//	"where user_id ='$uid' ";
//	$all=$GLOBALS['db']->getAll($sql);
//	echo json_encode($all);

//}
/* 获取我评论回复列表息列表*/
elseif ($act == 'get_message_list')
{
	$uid  = isset($_GET['uid']) ? $_GET['uid'] :  1;
	$pageNo=isset($_GET['pageNo']) ? $_GET['pageNo'] : 0 ;
	$pageSize=isset($_GET['pageSize']) ? $_GET['pageSize'] : 10 ;
	$pageNo=$pageNo-1;
	$sql  = "select m.add_time,c.cat_name,m.message,m.add_time from ".$GLOBALS['ecs']->table('user_message')." as m ".
	" left join ".$GLOBALS['ecs']->table('message_cat')." as c on c.cat_id=m.cat_id ".
	"where m.user_id ='$uid' ".
	"limit ".$pageNo*$pageSize." , ".$pageSize;
	$all=$GLOBALS['db']->getAll($sql);
	foreach($uu as $key=> $var){
		$uu[$key]['add_time'] = local_date($GLOBALS['_CFG']['time_format'],$uu[$key]['add_time']);
	}
	echo json_encode($all);

}
/* 获取我评论回复列表息列表*/
elseif ($act == 'get_mycomment_list')
{
//	$bid  = isset($_GET['bid']) ? $_GET['bid'] :  '';
	$uid  = isset($_GET['uid']) ? $_GET['uid'] :  1;
	$pageNo=isset($_GET['pageNo']) ? $_GET['pageNo'] : 0 ;
	$pageSize=isset($_GET['pageSize']) ? $_GET['pageSize'] : 10 ;
	$pageNo=$pageNo-1;
//	$sql  = "select m.* from ".$GLOBALS['ecs']->table('article_comment')." as m ".
////	" left join ".$GLOBALS['ecs']->table('message_cat')." as c on c.cat_id=m.cat_id ".
//	"where m.user_id ='$uid' ";
//	$all=$GLOBALS['db']->getAll($sql);
	$sql = " select g.id,a.content,a.comment_type,a.comment_id,a.id_value,a.good_count,a.add_time,a.parent_id,a.parent_user_id,a.parent_user_name,a.parent_user_nick,u.user_nick,u.user_name,u.user_id,u.avatar from ".$GLOBALS['ecs']->table('article_comment')." as a ".
	" left join ".$GLOBALS['ecs']->table('users')." as u ON a.user_id=u.user_id".
	" left join ".$GLOBALS['ecs']->table('good_mark')." as g on g.comment_id=a.comment_id and g.user_id='$uid'".
	" where a.user_id ='$uid' order by a.add_time desc  ".
	"limit ".$pageNo*$pageSize." , ".$pageSize;
	$uu=$GLOBALS['db']->getAll($sql);
	foreach($uu as $key=> $var){
		$uu[$key]['add_time'] = local_date($GLOBALS['_CFG']['time_format'],$uu[$key]['add_time']);
		$uu[$key]['avatar'] = OSS_HOST.$uu[$key]['avatar'];
		$uu[$key]['parent_id'] =intval($uu[$key]['parent_id']);
		$uu[$key]['comment_type'] =intval($uu[$key]['comment_type']);
		$uu[$key]['parent_user_id'] =intval($uu[$key]['parent_user_id']);
		$uu[$key]['show_type']=0;
		if($uu[$key]['comment_type'])
		{
			$uu[$key]['show_type'] = intval($GLOBALS['db']->getone('SELECT ac.show_type FROM ' . $ecs->table('article') . ' AS a '.
			'LEFT JOIN ' . $ecs->table('article_cat') . ' AS ac ON a.cat_id= ac.cat_id '.
			' WHERE a.article_id = ' . $uu[$key]['id_value']));
		}
			if($uu[$key]['parent_id']==0){
				$uu[$key]['show']=0;
			}else{
			
				if($uid==$uu[$key]['parent_user_id']){
					$uu[$key]['show']=0;
				}else{
					$uu[$key]['show']=1;
				}
			}
	}

	echo json_encode($uu);

}
/* 注册会员的处理 */
elseif ($act == 'app_register')
{
		include_once(ROOT_PATH . 'includes/lib_passport.php');

		$username = isset($_GET['uname']) ? $_GET['uname'] : '';
		$password = isset($_GET['pwd']) ? $_GET['pwd'] : '';
		$a=rand(1,1000);
		$b=rand(1,1000);
		$c=rand(1,1000);
		$d=$a.$b.$c.'@qq.com';
		$email	= isset($_GET['email']) ? trim($_GET['email']) : $d;
		if (app_register($username, $password, $email) !== false)
		{
			/*把新注册用户的扩展信息插入数据库*/
//			$sql = 'SELECT id FROM ' . $ecs->table('reg_fields') . ' WHERE type = 0 AND display = 1 ORDER BY dis_order, id';   //读出所有自定义扩展字段的id
//			$fields_arr = $db->getAll($sql);
//
//			$extend_field_str = '';	//生成扩展字段的内容字符串
//			foreach ($fields_arr AS $val)
//			{
//				$extend_field_index = 'extend_field' . $val['id'];
//				if(!empty($_POST[$extend_field_index]))
//				{
//					$temp_field_content = strlen($_POST[$extend_field_index]) > 100 ? mb_substr($_POST[$extend_field_index], 0, 99) : $_POST[$extend_field_index];
//					$extend_field_str .= " ('" . $_SESSION['user_id'] . "', '" . $val['id'] . "', '" . compile_str($temp_field_content) . "'),";
//				}
//			}
//			$extend_field_str = substr($extend_field_str, 0, -1);
//
//			if ($extend_field_str)	  //插入注册扩展数据
//			{
//				$sql = 'INSERT INTO '. $ecs->table('reg_extend_info') . ' (`user_id`, `reg_field_id`, `content`) VALUES' . $extend_field_str;
//				$db->query($sql);
//			}
//
//			/* 写入密码提示问题和答案 */
//			if (!empty($passwd_answer) && !empty($sel_question))
//			{
//				$sql = 'UPDATE ' . $ecs->table('users') . " SET `passwd_question`='$sel_question', `passwd_answer`='$passwd_answer'  WHERE `user_id`='" . $_SESSION['user_id'] . "'";
//				$db->query($sql);
//			}
//
//			$ucdata = empty($user->ucdata)? "" : $user->ucdata;
//			$Loaction = 'index.php';
//			ecs_header("Location: $Loaction\n");
			$sql="select user_id from".$GLOBALS['ecs']->table('users')." where user_name = '$username'";
			$user_id=$db->getOne($sql);
			$uu['user_name']=$username;
			$uu['user_id']=$user_id;
			$uu['error']=0;
			echo json_encode($uu);

		}else{
			
		}


		

}
/* 注册会员的处理 */
elseif ($act == 'act_register')
{
		include_once(ROOT_PATH . 'includes/lib_passport.php');

		$username = isset($_POST['username']) ? trim($_POST['username']) : '';
		$password = isset($_POST['password']) ? trim($_POST['password']) : '';
		$email	= isset($_POST['email']) ? trim($_POST['email']) : '';
		$other['msn'] = isset($_POST['extend_field1']) ? $_POST['extend_field1'] : '';
		$other['qq'] = isset($_POST['extend_field2']) ? $_POST['extend_field2'] : '';
		$other['office_phone'] = isset($_POST['extend_field3']) ? $_POST['extend_field3'] : '';
		$other['home_phone'] = isset($_POST['extend_field4']) ? $_POST['extend_field4'] : '';
		$other['mobile_phone'] = isset($_POST['extend_field5']) ? $_POST['extend_field5'] : '';
		$sel_question = empty($_POST['sel_question']) ? '' : compile_str($_POST['sel_question']);
		$passwd_answer = isset($_POST['passwd_answer']) ? compile_str(trim($_POST['passwd_answer'])) : '';

		$back_act = isset($_POST['back_act']) ? trim($_POST['back_act']) : '';

		if (m_register($username, $password, $email, $other) !== false)
		{
			/*把新注册用户的扩展信息插入数据库*/
			$sql = 'SELECT id FROM ' . $ecs->table('reg_fields') . ' WHERE type = 0 AND display = 1 ORDER BY dis_order, id';   //读出所有自定义扩展字段的id
			$fields_arr = $db->getAll($sql);

			$extend_field_str = '';	//生成扩展字段的内容字符串
			foreach ($fields_arr AS $val)
			{
				$extend_field_index = 'extend_field' . $val['id'];
				if(!empty($_POST[$extend_field_index]))
				{
					$temp_field_content = strlen($_POST[$extend_field_index]) > 100 ? mb_substr($_POST[$extend_field_index], 0, 99) : $_POST[$extend_field_index];
					$extend_field_str .= " ('" . $_SESSION['user_id'] . "', '" . $val['id'] . "', '" . compile_str($temp_field_content) . "'),";
				}
			}
			$extend_field_str = substr($extend_field_str, 0, -1);

			if ($extend_field_str)	  //插入注册扩展数据
			{
				$sql = 'INSERT INTO '. $ecs->table('reg_extend_info') . ' (`user_id`, `reg_field_id`, `content`) VALUES' . $extend_field_str;
				$db->query($sql);
			}

			/* 写入密码提示问题和答案 */
			if (!empty($passwd_answer) && !empty($sel_question))
			{
				$sql = 'UPDATE ' . $ecs->table('users') . " SET `passwd_question`='$sel_question', `passwd_answer`='$passwd_answer'  WHERE `user_id`='" . $_SESSION['user_id'] . "'";
				$db->query($sql);
			}

			$ucdata = empty($user->ucdata)? "" : $user->ucdata;
			$Loaction = 'index.php';
			ecs_header("Location: $Loaction\n");
		}
}
/* 增加收货地址 */
elseif ($act == 'add_address')
{
	include_once('includes/lib_transaction.php');        
	 /* 取得国家列表、商店所在国家、商店所在国家的省列表 */
	$smarty->assign('country_list',       get_regions());
	$smarty->assign('shop_country',       $_CFG['shop_country']);
	$smarty->assign('shop_province_list', get_regions(1, $_CFG['shop_country']));
    $consignee_list = get_consignee_list($_SESSION['user_id']);
	/* 取得每个收货地址的省市区列表 */
	$province_list = array();
	$city_list = array();
	$district_list = array();
	foreach ($consignee_list as $region_id => $consignee)
	{
		$consignee['country']  = isset($consignee['country'])  ? intval($consignee['country'])  : 0;
		$consignee['province'] = isset($consignee['province']) ? intval($consignee['province']) : 0;
		$consignee['city']     = isset($consignee['city'])     ? intval($consignee['city'])     : 0;

		$province_list = get_regions(1, $consignee['country']);
		$city_list     = get_regions(2, $consignee['province']);
		$district_list = get_regions(3, $consignee['city']);
	}
	$smarty->assign('province_list', $province_list);
	$smarty->assign('city_list',     $city_list);
	$smarty->assign('district_list', $district_list);	
	$smarty->assign('action', "user.php?act=add_edit_address");
	$smarty->assign('fun', 'add');
	$smarty->display('address_list.dwt');
}
/* 收货地址列表 */
elseif ($act == 'address_list')
{
	include_once('includes/lib_transaction.php');        
	 /* 取得国家列表、商店所在国家、商店所在国家的省列表 */
	$smarty->assign('country_list',       get_regions());
	$smarty->assign('shop_country',       $_CFG['shop_country']);
	$smarty->assign('shop_province_list', get_regions(1, $_CFG['shop_country']));
    $consignee_list = get_consignee_list($_SESSION['user_id']);
	/* 取得每个收货地址的省市区列表 */
	$province_list = array();
	$city_list = array();
	$district_list = array();
	foreach ($consignee_list as $region_id => $consignee)
	{
		$consignee['country']  = isset($consignee['country'])  ? intval($consignee['country'])  : 0;
		$consignee['province'] = isset($consignee['province']) ? intval($consignee['province']) : 0;
		$consignee['city']     = isset($consignee['city'])     ? intval($consignee['city'])     : 0;

		$province_list = get_regions(1, $consignee['country']);
		$city_list     = get_regions(2, $consignee['province']);
		$district_list = get_regions(3, $consignee['city']);
	}
	$smarty->assign('province_list', $province_list);
	$smarty->assign('city_list',     $city_list);
	$smarty->assign('district_list', $district_list);	
	$smarty->assign('consignee', $consignee_list);
    $smarty->assign('action', "user.php?act=act_edit_address");
    $smarty->assign('subval', '修改送货地址');
    $smarty->assign('fun', 'list');
    $smarty->display('address_list.dwt');
}
/*更新收获地址*/
elseif ($act == 'act_edit_address'){
	
	global $db;
	include_once('includes/lib_transaction.php');
	
	if(empty($_POST['country']) || empty($_POST['province']) || empty($_POST['city']) || empty($_POST['district']))
    {
        echo '<script language=javascript>alert("配送区域不可为空！");history.go(-1);</script>';
        exit;
    }
    if(empty($_POST['address']))
    {
        echo '<script language=javascript>alert("收货地址不可为空！");history.go(-1);</script>';
        exit;
    }
	if(empty($_POST['consignee']))
    {
        echo '<script language=javascript>alert("收货人姓名不可为空！");history.go(-1);</script>';
        exit;
    }
    if(empty($_POST['tel']))
    {
        echo '<script language=javascript>alert("联系电话不可为空！");history.go(-1);</script>';
        exit;
    }
    if(empty($_POST['mobile']))
    {
        echo '<script language=javascript>alert("联系手机不可为空！");history.go(-1);</script>';
        exit;
    }
    if(empty($_POST['email']))
    {
        echo '<script language=javascript>alert("电子邮箱不可为空！");history.go(-1);</script>';
        exit;
    }
	/*
	 * 保存收货人信息
	 */
	$consignee = array(
		'user_id'		=> $_SESSION['user_id'],
		'address_id'    => empty($_POST['address_id']) ? 0  : intval($_POST['address_id']),
		'consignee'     => empty($_POST['consignee'])  ? '' : trim($_POST['consignee']),
		'country'       => empty($_POST['country'])    ? '' : $_POST['country'],
		'province'      => empty($_POST['province'])   ? '' : $_POST['province'],
		'city'          => empty($_POST['city'])       ? '' : $_POST['city'],
		'district'      => empty($_POST['district'])   ? '' : $_POST['district'],
		'email'         => empty($_POST['email'])      ? '' : $_POST['email'],
		'address'       => empty($_POST['address'])    ? '' : $_POST['address'],
		'zipcode'       => empty($_POST['zipcode'])    ? '' : make_semiangle(trim($_POST['zipcode'])),
		'tel'           => empty($_POST['tel'])        ? '' : make_semiangle(trim($_POST['tel'])),
		'mobile'        => empty($_POST['mobile'])     ? '' : make_semiangle(trim($_POST['mobile'])),
		'sign_building' => empty($_POST['sign_building']) ? '' : $_POST['sign_building'],
		'best_time'     => empty($_POST['best_time'])  ? '' : $_POST['best_time'],
		'default_id'    => empty($_POST['default_id'])  ? '0' : $_POST['default_id'],
	);
	
	$result = update_address($consignee);
	
	$GLOBALS['db']->query("UPDATE " . $GLOBALS['ecs']->table('user_address') . " SET default_id = 0 WHERE default_id != 1 ");
	
	if($result){
        echo '<script language=javascript>alert("修改收货地址成功");location.href="user.php?act=address_list";</script>';
	}
	else{
        echo '<script language=javascript>alert("修改失败");history.go(-1);</script>';
	}
	if ($_SESSION['user_id'] > 0)
    {
        $smarty->assign('user_name', $_SESSION['user_name']);
    }
}
/*增加收获地址*/
elseif ($act == 'add_edit_address'){
	
	global $db;
	include_once('includes/lib_transaction.php');
	
	if(empty($_POST['country']) || empty($_POST['province']) || empty($_POST['city']) || empty($_POST['district']))
    {
        echo '<script language=javascript>alert("配送区域不可为空！");history.go(-1);</script>';
        exit;
    }
    if(empty($_POST['address']))
    {
        echo '<script language=javascript>alert("收货地址不可为空！");history.go(-1);</script>';
        exit;
    }
	if(empty($_POST['consignee']))
    {
        echo '<script language=javascript>alert("收货人姓名不可为空！");history.go(-1);</script>';
        exit;
    }
    if(empty($_POST['tel']))
    {
        echo '<script language=javascript>alert("联系电话不可为空！");history.go(-1);</script>';
        exit;
    }
    if(empty($_POST['mobile']))
    {
        echo '<script language=javascript>alert("联系手机不可为空！");history.go(-1);</script>';
        exit;
    }
    if(empty($_POST['email']))
    {
        echo '<script language=javascript>alert("电子邮箱不可为空！");history.go(-1);</script>';
        exit;
    }
	/*
	 * 保存收货人信息
	 */
	$consignee = array(
		'user_id'		=> $_SESSION['user_id'],
		'address_id'    => empty($_POST['address_id']) ? 0  : intval($_POST['address_id']),
		'consignee'     => empty($_POST['consignee'])  ? '' : trim($_POST['consignee']),
		'country'       => empty($_POST['country'])    ? '' : $_POST['country'],
		'province'      => empty($_POST['province'])   ? '' : $_POST['province'],
		'city'          => empty($_POST['city'])       ? '' : $_POST['city'],
		'district'      => empty($_POST['district'])   ? '' : $_POST['district'],
		'email'         => empty($_POST['email'])      ? '' : $_POST['email'],
		'address'       => empty($_POST['address'])    ? '' : $_POST['address'],
		'zipcode'       => empty($_POST['zipcode'])    ? '' : make_semiangle(trim($_POST['zipcode'])),
		'tel'           => empty($_POST['tel'])        ? '' : make_semiangle(trim($_POST['tel'])),
		'mobile'        => empty($_POST['mobile'])     ? '' : make_semiangle(trim($_POST['mobile'])),
		'sign_building' => empty($_POST['sign_building']) ? '' : $_POST['sign_building'],
		'best_time'     => empty($_POST['best_time'])  ? '' : $_POST['best_time'],
	);
	
	$result = update_address($consignee);
	if($result){
        echo '<script language=javascript>alert("增加收货地址成功");location.href="user.php?act=address_list";</script>';
	}
	else{
        echo '<script language=javascript>alert("增加收货地址失败");history.go(-1);</script>';
	}
	if ($_SESSION['user_id'] > 0)
    {
        $smarty->assign('user_name', $_SESSION['user_name']);
    }
}
/* 删除收货人信息*/
elseif ($act == 'drop_address')
{
	include_once('includes/lib_transaction.php');

	$consignee_id = intval($_GET['id']);

	if (drop_consignee($consignee_id))
	{
		ecs_header("Location: user.php?act=address_list\n");
		exit;
	}
}
/* 添加收藏商品(ajax) */
elseif ($act == 'collect')
{
	include_once(ROOT_PATH .'includes/cls_json.php');
	$json = new JSON();
	$result = array('error' => 0, 'message' => '');
	$goods_id = $_GET['id'];

	if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] == 0)
	{
		$result['error'] = 1;
		$result['message'] = "由于您还没有登录，因此您还不能使用该功能。";
		die($json->encode($result));
	}
	else
	{
		/* 检查是否已经存在于用户的收藏夹 */
		$sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('collect_goods') .
			" WHERE user_id='$_SESSION[user_id]' AND goods_id = '$goods_id'";
		if ($GLOBALS['db']->GetOne($sql) > 0)
		{
			$result['error'] = 1;
			$result['message'] = "该商品已经存在于您的收藏夹中。";
			die($json->encode($result));
		}
		else
		{
			$time = gmtime();
			$sql = "INSERT INTO " .$GLOBALS['ecs']->table('collect_goods'). " (user_id, goods_id, add_time)" .
					"VALUES ('$_SESSION[user_id]', '$goods_id', '$time')";

			if ($GLOBALS['db']->query($sql) === false)
			{
				$result['error'] = 1;
				$result['message'] = $GLOBALS['db']->errorMsg();
				die($json->encode($result));
			}
			else
			{
				$result['error'] = 0;
				$result['message'] = "该商品已经成功地加入了您的收藏夹。";
				die($json->encode($result));
			}
		}
	}
}
/* 用户中心 */
else
{
	if ($_SESSION['user_id'] > 0)
	{
		show_user_center();
	}
	else
	{
		$reuser_name= isset($_COOKIE['ECS']['reuser_name']) ? $_COOKIE['ECS']['reuser_name'] : '';
		if(!empty($reuser_name)){
			$smarty->assign('reuser_name', $reuser_name);
		}
		$smarty->assign('footer', get_footer());
		$smarty->display('login.dwt');
		exit;
	}
}

/**
 * 用户中心显示
 */
function show_user_center()
{
    include_once(ROOT_PATH .'includes/lib_clips.php');
	$best_goods = get_recommend_goods('best');
	if (count($best_goods) > 0)
	{
		foreach  ($best_goods as $key => $best_data)
		{
			$best_goods[$key]['shop_price'] = encode_output($best_data['shop_price']);
			$best_goods[$key]['name'] = encode_output($best_data['name']);
		}
	}
	//22:18 2013-7-16
	$rank_name = $GLOBALS['db']->getOne('SELECT rank_name FROM ' . $GLOBALS['ecs']->table('user_rank') . ' WHERE rank_id = '.$_SESSION['user_rank']);
	$GLOBALS['smarty']->assign('info', get_user_default($_SESSION['user_id']));
	$GLOBALS['smarty']->assign('rank_name', $rank_name);
	$GLOBALS['smarty']->assign('user_info', get_user_info());
	$GLOBALS['smarty']->assign('best_goods' , $best_goods);
	$GLOBALS['smarty']->assign('footer', get_footer());
	$GLOBALS['smarty']->display('user.dwt');
}

/**
 * app注册
 */
function app_register($username, $password ,$email)
{
	/* 检查username */
	if (empty($username))
	{

		$uu['message']='用户名必须填写';
		$uu['error']=1;
		echo json_encode($uu);
		
		return false;
	}
	if (preg_match('/\'\/^\\s*$|^c:\\\\con\\\\con$|[%,\\*\\"\\s\\t\\<\\>\\&\'\\\\]/', $username))
	{

		$uu['message']='用户名错误';
		$uu['error']=1;
		echo json_encode($uu);
		return false;
	}

	/* 检查是否和管理员重名 */
	if (admin_registered($username))
	{

		$uu['message']='此用户已存在';
		$uu['error']=1;
		echo json_encode($uu);
		return false;
	}

	if (!$GLOBALS['user']->add_user($username, $password, $email))
	{

		$uu['message']='注册失败';
		$uu['error']=1;
		echo json_encode($uu);
		//注册失败
		return false;
	}
	else
	{
		//注册成功
//		$uu['username']=$username;
//		$uu['error']=0;
//		echo json_encode($uu);
//		$sql="select user_id from".$GLOBALS['ecs']->table('users')." where user_name = '$user_name'";
//		$user_id=$db->getOne($sql);
//		$uu['username']=$user_name;
//		$uu['user_id']=$user_id;
//		$uu['error']=0;
//		echo json_encode($uu);
//		/* 设置成登录状态 */
//		$GLOBALS['user']->set_session($username);
//		$GLOBALS['user']->set_cookie($username);
	}

//		//定义other合法的变量数组
//		$other_key_array = array('msn', 'qq', 'office_phone', 'home_phone', 'mobile_phone');
//		$update_data['reg_time'] = local_strtotime(local_date('Y-m-d H:i:s'));
//		if ($other)
//		{
//			foreach ($other as $key=>$val)
//			{
//				//删除非法key值
//				if (!in_array($key, $other_key_array))
//				{
//					unset($other[$key]);
//				}
//				else
//				{
//					$other[$key] =  htmlspecialchars(trim($val)); //防止用户输入javascript代码
//				}
//			}
//			$update_data = array_merge($update_data, $other);
//		}
//		$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('users'), $update_data, 'UPDATE', 'user_id = ' . $_SESSION['user_id']);
//
//		update_user_info();	  // 更新用户信息
//      $Loaction = 'user.php?act=user_center';
//      ecs_header("Location: $Loaction\n");
		return true;

}

/**
 * 手机注册
 */
function m_register($username, $password, $email, $other = array())
{
	/* 检查username */
	if (empty($username))
	{
		echo '<script>alert("用户名必须填写！");window.location.href="user.php?act=register"; </script>';
		return false;
	}
	if (preg_match('/\'\/^\\s*$|^c:\\\\con\\\\con$|[%,\\*\\"\\s\\t\\<\\>\\&\'\\\\]/', $username))
	{
		echo '<script>alert("用户名错误！");window.location.href="user.php?act=register"; </script>';
		return false;
	}

	/* 检查是否和管理员重名 */
	if (admin_registered($username))
	{
		echo '<script>alert("此用户已存在！");window.location.href="user.php?act=register"; </script>';
		return false;
	}

	if (!$GLOBALS['user']->add_user($username, $password, $email))
	{
		echo '<script>alert("注册失败！");window.location.href="user.php?act=register"; </script>';
		//注册失败
		return false;
	}
	else
	{
		//注册成功

		/* 设置成登录状态 */
		$GLOBALS['user']->set_session($username);
		$GLOBALS['user']->set_cookie($username);
	}

		//定义other合法的变量数组
		$other_key_array = array('msn', 'qq', 'office_phone', 'home_phone', 'mobile_phone');
		$update_data['reg_time'] = local_strtotime(local_date('Y-m-d H:i:s'));
		if ($other)
		{
			foreach ($other as $key=>$val)
			{
				//删除非法key值
				if (!in_array($key, $other_key_array))
				{
					unset($other[$key]);
				}
				else
				{
					$other[$key] =  htmlspecialchars(trim($val)); //防止用户输入javascript代码
				}
			}
			$update_data = array_merge($update_data, $other);
		}
		$GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('users'), $update_data, 'UPDATE', 'user_id = ' . $_SESSION['user_id']);

		update_user_info();	  // 更新用户信息
        $Loaction = 'user.php?act=user_center';
        ecs_header("Location: $Loaction\n");
		return true;

}
?>